package com.spica.spicaschool.ui.group

import android.annotation.SuppressLint
import android.graphics.Color
import android.transition.Transition
import android.transition.TransitionManager
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.navigation.findNavController
import com.drakeet.multitype.MultiTypeAdapter
import com.fondesa.recyclerviewdivider.dividerBuilder
import com.google.android.material.transition.platform.MaterialArcMotion
import com.google.android.material.transition.platform.MaterialContainerTransform
import com.spica.spicaschool.R
import com.spica.spicaschool.base.BaseFragment
import com.spica.spicaschool.base.ILoadMoreAdapter
import com.spica.spicaschool.base.LoadMoreAdapterWrapper
import com.spica.spicaschool.bean.PageEntity
import com.spica.spicaschool.bean.group.Group
import com.spica.spicaschool.databinding.FragmentGroupListBinding
import com.spica.spicaschool.ui.main.MainFragmentDirections
import com.spica.spicaschool.utils.SpUtils
import com.spica.spicaschool.utils.TOKEN_SIGN
import com.spica.spicaschool.utils.UiUtils
import com.spica.spicaschool.viewmodel.GroupViewModel
import dagger.hilt.android.AndroidEntryPoint
import timber.log.Timber


/**
 * 小组
 */
@AndroidEntryPoint
class GroupFragment : BaseFragment<FragmentGroupListBinding>(), ILoadMoreAdapter,
    LoadMoreAdapterWrapper.OnClickRetryListener {

    private lateinit var showTransform: Transition

    private lateinit var endTransform: Transition

    private val viewModel by viewModels<GroupViewModel>()

    private val page = PageEntity()

    private val items = mutableListOf<Group>()

    private lateinit var adapter: MultiTypeAdapter

    private var isOk = false // 是否完成View初始化

    private var isFirst = true // 是否为第一次加载

    private var isError = false

    private var isLoading = false

    override fun setupViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentGroupListBinding = FragmentGroupListBinding.inflate(inflater, container, false)


    override fun onResume() {
        super.onResume()
        initLoadData()
    }

    override fun init() {
        initAnim()
        //点击Fab
        viewBinding.ivMenu.setOnClickListener {
            showMenu()
        }
        //点击菜单项
        viewBinding.btnCreateGroup.setOnClickListener {
            requireActivity().findNavController(R.id.fragment_container_view)
                .navigate(MainFragmentDirections.actionHomeToCreateGroupFragment())
            closeMenu()
        }
        viewBinding.btnSearchGroup.setOnClickListener {
            closeMenu()
        }
        initData()
    }

    private fun showMenu() {
        TransitionManager.beginDelayedTransition(viewBinding.root, showTransform)
        viewBinding.ivMenu.visibility = View.GONE
        viewBinding.containerMenu.visibility = View.VISIBLE
    }


    private fun closeMenu() {
        TransitionManager.beginDelayedTransition(viewBinding.root, endTransform)
        viewBinding.ivMenu.visibility = View.VISIBLE
        viewBinding.containerMenu.visibility = View.GONE
    }


    private fun initData() {
        // 初始化适配器
        adapter = MultiTypeAdapter()
        // 多类型列表注册多适配器
        adapter.register(GroupDelegate(requireActivity()))
        // 获取数据源
        adapter.items = items
        adapter.setHasStableIds(true) // 做diff
        viewBinding.rvList.adapter = LoadMoreAdapterWrapper(
            requireContext(),
            adapter, this,
            this
        )

        //设置分割线
        requireContext()
            .dividerBuilder()
            .size(8, TypedValue.COMPLEX_UNIT_DIP)
            .asSpace()
            .showLastDivider()
            .showFirstDivider()
            .build()
            .addTo(viewBinding.rvList)


        viewBinding.layoutSwipe.setOnRefreshListener {
            onLoadData(isRefresh = true)
        }
        isOk = true
    }

    /**
     * 初始化动画
     */
    private fun initAnim() {
        showTransform = MaterialContainerTransform().apply {
            startView = viewBinding.ivMenu
            endView = viewBinding.containerMenu
            addTarget(endView)
            pathMotion = MaterialArcMotion()
            scrimColor = Color.TRANSPARENT
            duration = 500L
        }

        endTransform = MaterialContainerTransform().apply {
            endView = viewBinding.ivMenu
            startView = viewBinding.containerMenu
            addTarget(endView)
            pathMotion = MaterialArcMotion()
            scrimColor = Color.TRANSPARENT
            duration = 500L
        }
    }


    @SuppressLint("NotifyDataSetChanged")
    private fun initLoadData() {
        if (isOk && isFirst) {
            viewModel.fetchDiaryList(
                onError = {
                    isError = true
                    Timber.e("请求过程发生错误：$it")
                },
                onComplete = {
                    isLoading = false
                    Timber.e("请求结束")
                },
                onStart = {
                    isLoading = false
                    isLoading = true
                    Timber.e("请求开始")
                },
                token = SpUtils.getSpValue(
                    context = requireContext(),
                    key = TOKEN_SIGN,
                    defaultVal = ""
                )
            )
            //初始化数据监听
            viewModel.groupsLiveData.observe(this) {
                page.nextPage = it.pageInfo.nextPage
                items.addAll(it.data)
                UiUtils.doMainThreadle({
                    viewBinding.layoutSwipe.isRefreshing = false
                })
                adapter.notifyDataSetChanged()
            }
            // 加载数据时判断是否完成view的初始化，以及是不是第一次加载此数据
            onLoadData(true)
            isFirst = false // 加载第一次数据后改变状态，后续不再重复加载
        }
    }

    /**
     * 加载数据
     * isRefresh：是否刷新
     **/
    @SuppressLint("NotifyDataSetChanged")
    private fun onLoadData(isRefresh: Boolean) {
        if (isRefresh) {
            isError = false
            items.clear()
            page.currentPage = 1
        }
        viewModel.pageChanged(PageEntity(currentPage = page.currentPage++))
    }

    // 加载更多
    private fun onLoadMore() {
        if (!page.nextPage) return else
            onLoadData(false)
    }


    override fun hasMoreResults(): Boolean {
        return page.nextPage
    }

    override fun hasError(): Boolean {
        return isError
    }

    override fun isLoading(): Boolean {
        if (!isLoading) {
            viewBinding.layoutSwipe.isRefreshing = false
        }
        return isLoading
    }

    //点击加载更多
    override fun onClickRetry() {
        Timber.e("加载更多...")
        onLoadMore()
    }
}